import base64
import copy
import hashlib
import json
from datetime import datetime, timedelta

from apps.model.apiBar.jdyxkapi import yxk_bar
from apps.model.apiBar.u9capi import u9c_bar
from apps.settingApi.api.chart.model import chartModel
from apps.settingApi.api.funs.model import funsModel
from apps.settingApi.api.basic.model import basicTypeModel
from apps.settingApi.api.printCode.model import printOrderModel
from apps.settingApi.api.timerTask.model import timerTaskConfigModel, timerTaskModel
from apps.settingApi.api.timerTask.task import add_task
from apps.settingApi.permission import barList, permissionDict1
from apps.settingApi.switchCase.casePrimaryKey import caseGetPrimaryKeyData
from apps.settingApi.api.users.model import usersModel, permissionModel, onLineModel
from apps.settingApi.api.lessees.model import lesseesModel
from comm.const import CHART01


# MD5加密
def userHashlib(data):
    """
    :param data: 需要加密的字符
    :return: 返回h5加密结果
    """
    # 创建一个 MD5 对象
    md5_hash = hashlib.md5()

    # 更新要加密的字符串
    md5_hash.update(str(data).encode('utf-8'))

    # 获取加密后的结果
    encrypted_string = md5_hash.hexdigest()
    return encrypted_string


# base64加密
def base64Jia(data):
    return base64.b64encode(str(data).encode()).decode()


# base64解密
def base64Jie(data):
    return base64.b64decode(data.encode()).decode()


# 初始化创建经销商以及用户
def userAddData(db):
    """
    用户基础资料新增
    :param db:
    :return:
    """
    # 获取当前日期
    current_date = datetime.now()
    # 将年份加100
    future_date = current_date + timedelta(days=100 * 365)
    # 创建经销商租户
    obj1 = lesseesModel.query.filter_by(id="000001").first()
    if obj1 is None:
        dataObj = {}
        dataObj["id"] = "000001"
        dataObj["name"] = "经销商"
        dataObj["type"] = 1
        dataObj["create_user"] = "root"
        dataObj["create_user"] = "root"
        dataObj['end_time'] = future_date
        lessees = lesseesModel(**dataObj)
        db.session.add(lessees)
        db.session.commit()
    # 创建经销商管理员账号
    obj1 = usersModel.query.filter_by(username="root").first()
    if obj1 is None:
        dataObj = {}
        id_z = caseGetPrimaryKeyData()
        dataObj["id"] = id_z
        dataObj["code"] = "root"
        dataObj["username"] = "root"
        dataObj["lessees_id"] = "000001"
        # dataObj["password"] = userHashlib('root')
        dataObj["password"] = base64Jia('root')
        dataObj["type"] = 1
        dataObj["create_user"] = id_z
        dataObj['end_time'] = future_date
        user = usersModel(**dataObj)
        db.session.add(user)
        db.session.commit()
    return


# 初始化创建菜单
def barAddData(db):
    barAddList = barList()
    barAddDataList = []
    for itm1 in barAddList:
        exit_id1 = db.session.query(funsModel).filter(funsModel.id == itm1['id']).first()
        if exit_id1 is None:
            itm1_z = copy.deepcopy(itm1)
            del itm1_z['children']
            barAddDataList.append(funsModel(**itm1_z))
        if len(itm1['children']) > 0:
            for itm2 in itm1['children']:
                exit_id2 = db.session.query(funsModel).filter(funsModel.id == itm2['id']).first()
                if exit_id2 is None:
                    del itm2['children']
                    itm2['parent_code'] = itm1['code']
                    barAddDataList.append(funsModel(**itm2))
    db.session.add_all(barAddDataList)
    db.session.commit()


# 创建基础权限选项
def permissionAddData(db):
    permissionDictData = permissionDict1()
    permissionAddDataList = []
    for itm1 in permissionDictData.keys():
        for itm2 in permissionDictData[itm1]['list']:
            permissionObj = {}
            permissionObj['funs_code'] = permissionDictData[itm1]['funs_code']
            permissionObj['name'] = permissionDictData[itm1]['name'] + '-' + itm2['name']
            permissionObj['code'] = itm1 + '-' + itm2['method']
            permissionObj['status'] = 1
            permissionObj['id'] = caseGetPrimaryKeyData()
            exit_id = db.session.query(permissionModel).filter(permissionModel.code == permissionObj['code']).first()
            if exit_id is None:
                permissionAddDataList.append(permissionModel(**permissionObj))
    db.session.add_all(permissionAddDataList)
    db.session.commit()


# 基础数据类型增加
def basicTypeAddData(db):
    basicTypeDictData = [
        {
            "id": "2024053114505639250008001",
            "label": "部门资料",
            "value": "dept",
            "sort": "10",
            "status": True,
        },
        {
            "id": "2024053114505639250008002",
            "label": "员工资料",
            "value": "salm",
            "sort": "20",
            "status": True,
        },
        {
            "id": "2024053114505639250008003",
            "label": "货品资料",
            "value": "prdt",
            "sort": "30",
            "status": True,
        },
        {
            "id": "2024053114505639250008004",
            "label": "数据库",
            "value": "dbpool",
            "sort": "30",
            "status": True,
        }
    ]
    basicTypeAddDataList = []
    for itm1 in basicTypeDictData:

        exit_id = db.session.query(basicTypeModel).filter(basicTypeModel.id == itm1['id']).first()
        if exit_id is None:
            basicTypeAddDataList.append(basicTypeModel(**itm1))
    db.session.add_all(basicTypeAddDataList)
    db.session.commit()


def printOrderAddData(db):
    printOrderDictData = [
        {
            "id": "2024053114505639250008001",
            "name": "部门资料",
            "code": "dept",
        },
        {
            "id": "2024053114505639250008002",
            "name": "员工资料",
            "code": "salm",
        },
        {
            "id": "2024053114505639250008003",
            "name": "货品资料",
            "code": "prdt",
        }
    ]
    printOrderAddDataList = []
    for itm1 in printOrderDictData:

        exit_id = db.session.query(printOrderModel).filter(printOrderModel.code == itm1['code']).first()
        if exit_id is None:
            itm1['id'] = caseGetPrimaryKeyData()
            printOrderAddDataList.append(printOrderModel(**itm1))
    db.session.add_all(printOrderAddDataList)
    db.session.commit()


# 程序启动时候删除全部在线用户
def onLineModelDelete(db):
    onLineModel.query.filter().delete()
    db.session.commit()


# 定时任务配置
def timerTaskConfigModelAdd(db):
    # 查询定时器配置是否存在
    exit_id = db.session.query(timerTaskConfigModel).filter(
        timerTaskConfigModel.id == '2024053114505639250008110').first()
    if exit_id is None:
        timerTaskConfig = {}
        timerTaskConfig["id"] = '2024053114505639250008110'
        timerTaskConfig["time"] = 5
        timerTaskConfig["status"] = True
        jobId = add_task(trigger='interval', seconds=5)
        timerTaskConfig["process"] = jobId
        db.session.add(timerTaskConfigModel(**timerTaskConfig))
        db.session.commit()
    # # 如果存在启动定时器
    # if exit_id != None:
    #     if exit_id.status == True:
    #         jobId = add_task(trigger='interval', seconds=exit_id.time)
    #         db.session.query(timerTaskConfigModel).filter().update(
    #             {"status": True, "process": jobId})
    #         db.session.commit()


def timerTaskModelAdd(db):
    addDataList = [*u9c_bar,*yxk_bar]

    for itm in addDataList:

        # 查询定时器配置是否存在
        exit_id = db.session.query(timerTaskModel).filter(
            timerTaskModel.id == itm["id"]).first()
        if exit_id is None:
            db.session.add(timerTaskModel(**itm))
            db.session.commit()

# 看板模板
def chartModelAdd(db):
    # 查询定时器配置是否存在
    exit_id = db.session.query(chartModel).filter(chartModel.id == '2024053114505639250008110').first()
    if exit_id is None:
        chartConfig = {}
        chartConfig["id"] = '2024053114505639250008110'
        chartConfig["name"] = '系统模板1'
        chartConfig["type"] = 1
        chartConfig["lessees_id"] = '000001'
        chartConfig["config"] = json.dumps(CHART01, ensure_ascii=False)
        db.session.add(chartModel(**chartConfig))
        db.session.commit()


def baseAddData(db):
    # 初始化创建经销商以及用户
    userAddData(db)
    # 初始化创建菜单
    barAddData(db)
    # 创建基础权限选项
    permissionAddData(db)
    # 创建基础数据类型
    basicTypeAddData(db)
    # 创建打印单据
    printOrderAddData(db)
    # 程序重启启动删除所有在线用户
    onLineModelDelete(db)
    # 增加定时任务配置
    timerTaskConfigModelAdd(db)
    # 初始化增加定时任务
    timerTaskModelAdd(db)
    # 初始化看板
    chartModelAdd(db)
    return
